<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Ajax_users extends CI_Controller {
    
    function Ajax_users()
    {
        parent::__construct();
    }
    
    function register()
    {
        $this->load->model('users_model');
        
        // Validate all user input
        $fields = array('last_name', 'first_name', 'username', 'password');
     
        $url    = '';
        $error  = '';
        
        foreach($fields as $field)
        {
            // ex. $field = 'last_name'; $field_title = 'Last Name'
            $field_title = ucwords(str_replace('_', ' ', $field));
            
            if(strcmp($this->input->post($field), '') == 0)
            {
                $error .= '<li>' . $field_title . ' is required</li>';
            }
            
            if(strcmp($field, 'username') == 0 || strcmp($field, 'password') == 0)
            {
                if(strcmp($field, 'username') == 0)
                {
                    if($this->users_model->check_username($this->input->post($field)))
                    {
                        $error .= '<li>' . $field_title . ' is already in use</li>';
                    }
                }
                
                if(strlen($this->input->post($field)) > 0 && strlen($this->input->post($field)) < 6)
                {
                    $error .= '<li>' . $field_title . ' must have a minimum of 6 characters</li>';
                }
            }
        }
        
        if(! $error)
        {
            $this->load->helper('date');
            
            $insert['register_date'] = now();
            
            foreach($fields as $field)
            {
                if(strcmp($field, 'password') == 0)
                {
                    $insert[$field] = md5($this->input->post($field));
                }
                else
                {
                    $insert[$field] = $this->input->post($field);
                }
            }
            
            $this->users_model->register($insert);
            
            $url = base_url() . 'login';
        }
        
        $return['url']      = $url;
        $return['error']    = $error;
        
        // Return
        echo json_encode($return);
    }
    
}

/* End of file ajax_users.php */
/* Location: ./application/controllers/ajax_users.php */